import { _decorator, Component, Node, Tween, tween, Vec3 } from 'cc';
import { AudioManager, Audios } from '../AshFramework/Managers/AudioManager';
import { NodeUtil } from '../AshFramework/Utils/NodeUtil';
import PrefsUtil from '../AshFramework/Utils/PrefsUtil';
import { Constant } from '../AshFramework/Datas/Constant';
import { Panel, UIManager } from '../AshFramework/Managers/UIManager';
import Banner from '../Banner';

const { ccclass, property } = _decorator;

@ccclass('SettingPanel')
export class SettingPanel extends Component {
    Panel: Node;
    MusicButton: Node;
    SFXButton: Node;
    VibrationButton: Node;

    protected onLoad(): void {
        this.Panel = NodeUtil.GetNode("Panel", this.node);
        this.MusicButton = NodeUtil.GetNode("MusicButton", this.node);
        this.SFXButton = NodeUtil.GetNode("SFXButton", this.node);
        this.VibrationButton = NodeUtil.GetNode("VibrationButton", this.node);
    }

    Show() {
        if (Banner.NeedShowMoreAd) {
            Banner.Instance.ShowBannerAd();
            Banner.Instance.ShowCustomAd();
        }

        this.RefreshButtonState();

        this.Panel.setScale(0, 0, 0);
        Tween.stopAllByTarget(this.Panel);

        tween(this.Panel).to(0.3, { scale: Vec3.ONE }, { easing: `backOut` }).call(() => { }).start();
    }

    RefreshButtonState() {
        this.SetButtonState(this.MusicButton, PrefsUtil.GetBool(Constant.Key.Music, true));
        this.SetButtonState(this.SFXButton, PrefsUtil.GetBool(Constant.Key.SFX, true));
        this.SetButtonState(this.VibrationButton, Banner.VibrateOn);
    }

    SetButtonState(node: Node, isOn: boolean) {
        node.getChildByName("0") && (node.getChildByName("0").active = !isOn);
        node.getChildByName("1") && (node.getChildByName("1").active = isOn);
    }

    OnButtonClick(event, data) {
        AudioManager.PlaySound(Audios.ButtonClick);

        switch (event.target.name) {
            case 'MusicButton':
                PrefsUtil.SetBool(Constant.Key.Music, !PrefsUtil.GetBool(Constant.Key.Music, true));
                this.RefreshButtonState();
                break;

            case 'SFXButton':
                PrefsUtil.SetBool(Constant.Key.SFX, !PrefsUtil.GetBool(Constant.Key.SFX, true));
                this.RefreshButtonState();
                break;

            case 'VibrationButton':
                Banner.VibrateOn = !Banner.VibrateOn;
                this.RefreshButtonState();
                break;

            case 'CloseButton':
                UIManager.GetInstance().HidePanel(Panel.SettingPanel);
                break;
        }
    }

}